//
//  TKYQuestionTypeController.m
//  StationHouseHelper
//
//  Created by apple on 2018/7/27.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYQuestionTypeController.h"
#import "TKYFindTreeViewCell.h"
#import "TKYQuestionTypeModel.h"
@interface TKYQuestionTypeController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)BaseTabelView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) TKYQuestionTypeModel *questionType;
@property (nonatomic, assign) NSInteger row;
@property (nonatomic, strong)NSMutableString * selectedStrM;// 拼接最后要显示的字符串
@property (nonatomic, strong) NSString *selectedStr1;/**第一层选中*/
@property (nonatomic, strong) NSString *selectedStr2;/**第2层选中*/
@property (nonatomic, strong) NSString *selectedStr3;/**第3层选中*/
@property (nonatomic, strong) NSString *selectedStr4;/**第4层选中*/
@end

@implementation TKYQuestionTypeController

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加监理单位列表
    [self.view addSubview:self.tableView];
    //设置导航
    [self setupNavigation];
    //请求数据
    //[self requestQuestionTypeDataWithID:nil];
    
    [self requestDataWithID:@"0"];
}

/**
 设置导航
 */
- (void)setupNavigation{
    self.navigationItem.title = @"问题类型";
    //设置导航栏文字颜色
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}


- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"TKYFindTreeViewCell";
    TKYFindTreeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[TKYFindTreeViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.questionTypeModel = self.dataSourceArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /**先遍历所有的数据为非选中*/
    for (TKYQuestionTypeModel *questionTypeModel in self.dataSourceArr) {
        questionTypeModel.isSelected = NO;
    }
    NSInteger row = indexPath.row;
    TKYQuestionTypeModel *model = _dataSourceArr[row];
    //model的isSelected 设置为选中, 只要选中isSelected 就是YES
    model.isSelected = YES;
    
    if (model.isOpen) {
        //原来是展开的，现在要收起,则删除model.detailArray存储的数据
        [self deleteObjectWithDataArray:model.detailArray count:0];
    }
    else {
        //如果是选中状态就给设置的每一次的字符串赋值
        if (model.isSelected == YES) {
            if (model.level == 0) {
                self.selectedStr1 = model.name;
            }else if(model.level == 1){
                self.selectedStr2 = model.name;
            }else if(model.level == 2){
                self.selectedStr3 = model.name;
            }else{
                self.selectedStr4 = model.name;
            }
        }
        NSMutableString *strM = [NSMutableString string];
        [strM appendString:model.name];
         NSLog(@"%@",strM);
        if ([model.isParent boolValue] == YES) {
            //原来是收起的，现在要展开，则需要将同层次展开的收起，然后再展开
            [self compareSameLevelWithModel:model row:row];
        }
        else {
            //初始化字符串为了拼接最后要返回的字符串
            self.selectedStrM = [NSMutableString string];
            //依次判断选择的层级有没有值如果有值就拼接
            if (self.selectedStr1.length > 0) {
                [self.selectedStrM appendFormat:@"%@",self.selectedStr1];
            }
            if (self.selectedStr2.length > 0){
                [self.selectedStrM appendFormat:@"->%@",self.selectedStr2];
            }
            if (self.selectedStr3.length > 0){
                [self.selectedStrM appendFormat:@"->%@",self.selectedStr3];
            }
            if (self.selectedStr4.length > 0){
                [self.selectedStrM appendFormat:@"->%@",self.selectedStr4];
            }
            NSLog(@"%@", [NSString stringWithFormat:@"%@",self.selectedStrM]);
            //点击的是最后一层数据，跳转到别的界面
            __weak typeof(self) weakSelf = self;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.selectedStrM preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                weakSelf.selectedQuestionTypeBlock(model);
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            NSLog(@"最后一层");
        }
    }
    model.isOpen = !model.isOpen;
    
    //滑动到屏幕顶部
    for (int i = 0; i < _dataSourceArr.count; i++) {
        TKYQuestionTypeModel *openModel = _dataSourceArr[i];
        if (openModel.isOpen && openModel.level == 0) {
            //将点击的cell滑动到屏幕顶部
            NSIndexPath *selectedPath = [NSIndexPath indexPathForRow:i inSection:0];
            [tableView scrollToRowAtIndexPath:selectedPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
    [tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (void)requestDataWithID:(NSString *)ids {
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&safeQualityFlag=1&pid=%@",kApiBaseUrl,KGetAllQuestionTypeUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],ids];
    //第一
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"]integerValue] == 0) {
            NSArray *arr = response[@"questionTypeList"];
            
            if (self.questionType) {
                self.questionType.detailArray = [NSMutableArray array];
                for (NSDictionary * dic in arr) {
                    //TKYFindTreeModel *model = [TKYFindTreeModel new];
                    TKYQuestionTypeModel *model =  [TKYQuestionTypeModel mj_objectWithKeyValues:dic];
                    model.isOpen = NO;
                    [self.questionType.detailArray addObject:model];
                }
                [self addObjectWithDataArray:self.questionType.detailArray row:self.row + 1];
            } else {
                for (NSDictionary * dic in arr) {
                    // TKYFindTreeModel *model = [TKYFindTreeModel new];
                    TKYQuestionTypeModel *model=  [TKYQuestionTypeModel mj_objectWithKeyValues:dic];
                    model.isOpen = NO;
                    [self.dataSourceArr addObject:model];
                }
            }
        }else{
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"===%@",error);
    }];
}

#pragma mark - 处理展开收起逻辑
/**
 在指定位置插入要展示的数据
 @param dataArray 数据数组
 @param row  需要插入的数组下标
 */
- (void)addObjectWithDataArray:(NSMutableArray *)dataArray row:(NSInteger)row {
    for (int i = 0; i < dataArray.count; i++) {
        TKYQuestionTypeModel *model = dataArray[i];
        model.isOpen = NO;
        [_dataSourceArr insertObject:model atIndex:row];
        row += 1;
    }
}

/**
 删除要收起的数据
 @param dataArray 数据
 @param count   统计删除数据的个数
 @return 删除数据的个数
 */
- (CGFloat)deleteObjectWithDataArray:(NSMutableArray *)dataArray count:(NSInteger)count {
    for (TKYQuestionTypeModel *model in dataArray) {
        count += 1;
        if (model.isOpen && [model.isParent boolValue] == YES) {
            count = [self deleteObjectWithDataArray:model.detailArray count:count];
        }
        model.isOpen = NO;
        [_dataSourceArr removeObject:model];
    }
    return count;
}

/**
 与点击同一层的数据比较，然后删除要收起的数据和插入要展开的数据
 @param model 点击的cell对应的model
 @param row  点击的在tableview的indexPath.row,也对应_resultArray的下标
 */
- (void)compareSameLevelWithModel:(TKYQuestionTypeModel *)model row:(NSInteger)row {
    NSInteger count = 0;
    NSInteger index = 0;  //需要收起的起始位置
    //如果直接用_resultArray，在for循环为完成之前，_resultArray会发生改变，使程序崩溃。
    NSMutableArray *copyArray = [_dataSourceArr mutableCopy];
    for (int i = 0; i < copyArray.count; i++) {
        TKYQuestionTypeModel *openModel = copyArray[i];
        if (openModel.level == model.level) {
            //同一个层次的比较
            if (openModel.isOpen) {
                //删除openModel所有的下一层
                count = [self deleteObjectWithDataArray:openModel.detailArray count:count];
                index = i;
                openModel.isOpen = NO;
                break;
            }
        }
    }
    
    //插入的位置在删除的位置的后面，则需要减去删除的数量。
    if (row > index && row > count) {
        row -= count;
    }
    self.questionType = model;
    self.row = row;
    [self requestDataWithID:model.ID];
}

@end
